<template>
  <div class="my">
    <div class="my-head">
      <span>个人中心</span>
    </div>
    <div class="my-content"></div>
    <div class="my-box">
      <div class="card">
        <div class="card-content">
          <img class="avatar" :src="avatarUrl" alt="头像" @click="triggerFileInput" />
          <div class="info">
            <div class="name">张三</div>
            <div class="id">ID: 12345 / 邀请码: ABCDE</div>
          </div>
        </div>
        <div class="footer-content">
          <div class="action-item" @click="navigateTo('/discount')">
            <div class="quantity">{{ couponCount }}</div>
            <div class="text">优惠券</div>
          </div>
          <div class="action-item" @click="navigateTo('/props')">
            <div class="quantity">{{ propCardCount }}</div>
            <div class="text">道具卡</div>
          </div>
        </div>
      </div>

      <!-- 新卡片 -->
      <div class="card new-card">
        <div class="card-content">
          <div class="action-item" @click="navigateTo('/delivery')">
            <van-icon name="gift-o" />
            <div class="text">待发货</div>
          </div>
          <div class="action-item" @click="navigateTo('/receipt')">
            <van-icon name="shopping-cart-o" />
            <div class="text">待收货</div>
          </div>
        </div>
      </div>

      <!-- 轮播图 -->
      <van-swipe class="my-swipe" autoplay="3000" indicator-color="white">
        <van-swipe-item v-for="(image, index) in carouselImages" :key="index">
          <img :src="image" class="swipe-image" />
        </van-swipe-item>
      </van-swipe>

      <!-- 九宫格 -->
      <van-grid>
        <van-grid-item icon="bill-o" text="消费账单" @click="navigateTo('/bill')" />
        <van-grid-item icon="friends-o" text="邀请好友" @click="navigateTo('/friends')" />
        <van-grid-item icon="home-o" text="收货地址" @click="navigateTo('/address')" />
        <van-grid-item icon="service-o" text="联系客服" @click="navigateTo('/services')" />
      </van-grid>
      <van-grid>
        <van-grid-item icon="question-o" text="帮助与反馈" @click="navigateTo('/help')" />
        <van-grid-item icon="contact-o" text="关于我们" @click="navigateTo('/us')" />
        <van-grid-item icon="setting-o" text="设置" @click="navigateTo('/set')" />
      </van-grid>
    </div>
    
    <!-- 隐藏的文件输入 -->
    <input 
      type="file"
      ref="fileInput"
      style="display: none;" 
      @change="handleFileChange"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { useBarrageStore } from '../../store/barrageStore';

const avatarUrl = ref('https://pic.aigexing.net/uploads/4/1253/995939230/92793696796/87969.jpg'); // 替换为实际的头像URL
const carouselImages = ref([
  'https://img1.baidu.com/it/u=1008918785,1651076751&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=500',
  'https://img1.baidu.com/it/u=1008918785,1651076751&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=500',
]);

const router = useRouter();

const form = ref({
  name: '',
  ID: '',
  Code: ''
});
const selectedFile = ref<File | null>(null);
const fileInput = ref<HTMLInputElement | null>(null);

const triggerFileInput = () => {
  if (fileInput.value) {
    fileInput.value.click();
  }
};

const handleFileChange = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const files = target.files;
  if (files && files[0]) {
    selectedFile.value = files[0];
    uploadImage();
  }
};

const uploadImage = async () => {
  if (!selectedFile.value) {
    alert('请选择文件');
    return;
  }

  const formData = new FormData();
  formData.append('image', selectedFile.value);
  formData.append('name', form.value.name);
  formData.append('ID', form.value.ID);
  formData.append('Code', form.value.Code);

  try {
    const response = await axios.post('http://localhost:3000', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    
    if (response.data.success) {
      alert('上传成功');
      avatarUrl.value = response.data.imgPath; // 更新头像URL
    }
  } catch (error) {
    console.error(error);
    alert('上传失败');
  }
};

const navigateTo = (path: string) => {
  router.push(path);
};

// 获取优惠券和道具卡的数据条数
const couponCount = ref(0); // 初始值为0
const propCardCount = ref(0); // 初始值为0

// 模拟从API获取数据
const fetchData = async () => {
  try {
    const couponResponse = await axios.get('http://localhost:3789/coupon');
    couponCount.value = couponResponse.data.data.length; // 确保提取data部分

    const propCardResponse = await axios.get('http://localhost:3789/prop');
    propCardCount.value = propCardResponse.data.data.length; // 确保提取data部分
  } catch (error) {
    console.error('获取数据失败', error);
  }
};

onMounted(() => {
  fetchData();
});

const barrageStore = useBarrageStore();
const barrages = barrageStore.barrages;

onMounted(() => {
  const updateInterval = window.setInterval(barrageStore.updateBarrages, 16);
  onUnmounted(() => {
    clearInterval(updateInterval);
  });
});
</script>

<style scoped>
.my {
  width: 100%;
  height: calc(100vh - 50px); /* 减去底部栏高度 */
  background-color: #f5f5f5;
  overflow-y: auto; /* 允许垂直滚动 */
  font-family: 'Helvetica Neue', Arial, sans-serif;
}

.my-head {
  width: 100%;
  height: 50px;
  line-height: 50px;
  text-align: center;
  background-color: #ffffff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.my-head span {
  font-size: 22px;
  font-weight: bold;
  color: #333333;
}

.my-content {
  width: 100%;
  height: 140px; /* 调整高度适配卡片 */
  background: linear-gradient(to bottom right, #ffebe9, #ffcccb);
  position: relative;
}

.my-box {
  width: calc(100% - 40px);
  margin: 20px auto; /* 水平居中，并且有一定的间隔 */
  z-index: 1;
  position: relative;
  top: -100px; /* 向上移动，使一部分卡片悬挂在my-content区内 */
}

.card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-top: 20px; /* 间隔20px */
}

.card-content {
  display: flex;
  align-items: center;
}

.avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  border: 2px solid #ffffff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer; /* 添加手形光标 */
}

.info {
  margin-left: 15px;
}

.name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.id {
  font-size: 14px;
  color: #888;
}

.footer-content {
  display: flex;
  justify-content: space-around;
  margin-top: 15px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.quantity {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.text {
  font-size: 14px;
  color: #888;
}

.new-card .card-content {
  display: flex;
  justify-content: space-around;
}

.icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 轮播图样式 */
.my-swipe {
  width: 100%;
  height: 120px; /* 确保轮播图高度足够显示椭圆形状 */
  margin: 20px 0; /* 上下间隔 20px */
}

.swipe-image {
  width: 100%; /* 确保与上面卡片的宽度对齐 */
  height: 120px;
  object-fit: cover;
  border-radius: 12px; /* 设置椭圆效果 */
}

.van-grid-item__content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80px;
  background-color: #e0e0e0;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.upload-section {
  margin: 20px auto;
  width: calc(100% - 40px);
}

.upload-section input {
  display: block;
  width: 100%;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.upload-section button {
  padding: 10px 20px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.upload-section button:hover {
  background-color: #0056b3;
}
</style>
